package cn.tedu.lbs.marketing.web.consumer;

import cn.tedu.lbs.marketing.web.service.ActivityService;
import cn.tedu.lbs.marketing.web.service.UserCouponService;
import com.tarena.lbs.pojo.basic.event.LocationEvent;
import com.tarena.lbs.pojo.marketing.param.UserCouponsParam;
import com.tarena.lbs.pojo.marketing.po.ActivityPO;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.cloud.stream.annotation.StreamListener;
import org.springframework.cloud.stream.annotation.StreamRetryTemplate;
import org.springframework.stereotype.Component;

import java.util.List;

@Component
@Slf4j
public class AutoReceiveCouponConsumer {
    @Autowired
    private ActivityService activityService;
    @Autowired
    private UserCouponService userCouponService;
    //自动下发优惠券消费方法
    @StreamListener("store-location-input")
    public void autoReceiveCoupon(LocationEvent event){
        log.info("自动下发优惠券消费开始执行,userId:{},storeId:{}",event.getUserId(),event.getStoreId());
        //1.将当前店铺 关联的活动 并且支持自动营销的活动 查询出来
        List<ActivityPO> activities=activityService.getMarketingActivities(event.getStoreId());
        //2.如果活动集合不为空 对活动遍历 封装领取优惠券param对象调用 优惠券领取功能
        if (activities!=null&&activities.size()>0){
            for (ActivityPO activity : activities) {
                UserCouponsParam userCouponsParam=new UserCouponsParam();
                userCouponsParam.setUserId(event.getUserId());
                userCouponsParam.setActivityId(activity.getId());
                userCouponsParam.setReceiveChannel(2);
                userCouponsParam.setShopId(event.getStoreId());
                userCouponsParam.setCouponId(activity.getRewardCouponId());
                try{
                    userCouponService.receiveCoupon(userCouponsParam);
                }catch (Exception e){
                    log.error("自动下发优惠券失败",e);
                }

            }
        }
    }
}
